package com.ruike.alisurface.services;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.ruike.alisurface.Constant;
import com.ruike.alisurface.Serials.MsgEventBus;
import com.ruike.alisurface.Serials.Ttys3Utils;
import com.ruike.alisurface.utils.CountTimeUtils;
import com.ruike.alisurface.utils.ShareKey;
import com.voodoo.lib_utils.L;
import com.voodoo.lib_utils.ShareUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Timer;
import java.util.TimerTask;


/**
 * 需求
 * 1.紫外线灯每计时周期内（暂定60分钟）开启2分钟（总累计时间）。
 * 2.灯开启时，触摸屏幕或检测到人体任意一项立即关闭，两项同时消失延时15秒开启紫外线灯，直到2分钟计时结束。
 * 3.只在安卓端人工开启紫外线灯不需要远程操作，人工开启后自动累计计时。
 * <p>
 * <p>
 * 紫外灯人体感应
 */
public class UvlampTimersService extends Service {
    String Tag = "紫外灯=";
    int totalcount = 3600;//总周期时间  秒
    int countTime = 120;//要开启的时间 秒
    boolean isSomeone = false;//是否在触摸
    boolean totalCycle = false;//监听总周期的
    CountTimeUtils timeUtils1;
    CountTimeUtils timeUtils2;
    CountTimeUtils timeUtils3;

    int mCurrentTime;//当前开启的时间

    @Override
    public void onCreate() {
        super.onCreate();
        EventBus.getDefault().register(this);
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        L.i(Tag, "   调起了紫外灯服务  ");

        totalcount = ShareUtils.getInstance().getInt(ShareKey.TOTAL_TIME, 3600);
        countTime = ShareUtils.getInstance().getInt(ShareKey.INTERVAL_TIME, 120);
        checkTimerBodyInduction();
        return super.onStartCommand(intent, flags, startId);

    }


    // 当一个Message Event提交的时候这个方法会被调用
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBusResult(MsgEventBus event) {
        if ("Uvlamp".equals(event.getType())) {
            L.i(Tag, " 收到了  " + event.getMessage());
            if (event.getMessage().contains("有触摸")) {
                isSomeone = true;
            } else {
                isSomeone = false;
            }
        }
    }


    /**
     * 总周期
     * 每个周期到了后重置 开启紫外灯时间 及一些其他变量
     * 循环周期执行
     */
    public void checkCycleLamp() {
        if (totalCycle) {
            L.i(Tag, "紫外灯周期   " + totalcount + "s 总周期已经在计时了  ");
            return;
        }
        totalcount = ShareUtils.getInstance().getInt(ShareKey.TOTAL_TIME, 3600);
        countTime = ShareUtils.getInstance().getInt(ShareKey.INTERVAL_TIME, 120);
        ShareUtils.getInstance().putInt(ShareKey.CURRENT_TIME, 0);
        L.i(Tag, "紫外灯周期    " + totalcount + "s  总周期 计时开始");
        totalCycle = true;
        if (timeUtils1 != null) {
            timeUtils1.cancel();
        }

        timeUtils1 = new CountTimeUtils(totalcount) {
            @Override
            public void onTick(long mMillisUntilFinished) {

            }

            @Override
            public void onFinish() {
                totalCycle = false;
                isCheckstatus = 0;
                L.i(Tag, "紫外灯周期   " + totalcount + "s 总周期 计时结束");
                checkCycleLamp();
            }
        }.start();

    }

    /**
     * 开启紫外灯周期
     * 开启和关闭之间的时间间隔以及开启多次时间的累加
     */
    public void checkCountTimeTwoLamp() {
        cancelTwoCountTime();
        mCurrentTime = ShareUtils.getInstance().getInt(ShareKey.CURRENT_TIME, 0);
        int times = countTime - mCurrentTime;
        if (times == 0) {
            L.i(Tag, "紫外灯周期  紫外灯开启时间已经完成  不需要再次开启了");
            return;
        }
        L.i(Tag, "紫外灯周期 " + times + "s  计时开始  开启紫外灯");
        sendLedLamp(false);
        timeUtils2 = new CountTimeUtils(times) {
            @Override
            public void onTick(long mMillisUntilFinished) {
                ShareUtils.getInstance().putInt(ShareKey.CURRENT_TIME, ++mCurrentTime);
                L.i(Tag, "紫外灯周期 " + times + "s  计时开始   ===" + mCurrentTime);
            }

            @Override
            public void onFinish() {
                isCheckstatus = 1;
                sendLedLamp(true);
                L.i(Tag, "紫外灯周期  " + times + "s 计时结束   关闭紫外灯");
            }
        }.start();

    }

    /**
     * 周期  15 s
     * <p>
     * 监听到无人触摸及感应到没有后延迟完毕后开启紫外灯
     */
    public void checkFifteenCountTimeLamp() {
        if (Constant.isSzwk || Constant.showShop) {
            L.i(Tag, Constant.isSzwk  , Constant.showShop,"  有在出货或者发送温控中，等待下次 ");
            isCheckstatus = 0;
            cancelFifteenCountTime();
            cancelTwoCountTime();
            return;
        }
        mCurrentTime = ShareUtils.getInstance().getInt(ShareKey.CURRENT_TIME, 0);
        int times = countTime - mCurrentTime;
        if (times == 0) {
            L.i(Tag, "紫外灯周期  紫外灯开启时间已经完成  不需要延迟15s后再次开启了");
            return;
        }
        L.i(Tag, "紫外灯周期  延时 5s  计时开始  准备紫外灯");
        cancelFifteenCountTime();
        cancelTwoCountTime();
        timeUtils3 = new CountTimeUtils(5) {
            @Override
            public void onTick(long mMillisUntilFinished) {

            }

            @Override
            public void onFinish() {
                L.i(Tag, "紫外灯周期  5s  计时结束 准备开启紫外灯");
                checkCountTimeTwoLamp();
            }
        }.start();
    }

    int isOffLinght = -1;//紫外灯是否已经关闭状态

    /**
     * 是否关闭紫外灯
     *
     * @param isclose true  关闭   false  开启
     */
    public void sendLedLamp(boolean isclose) {
        int isstatus = isclose ? 0 : 1;
        if (isclose) {
            cancelFifteenCountTime();
            cancelTwoCountTime();
        }
        if (isOffLinght == isstatus) {
            L.i(Tag, isclose ? " 已经关闭紫外灯指令 " : "已经开启紫外灯指令");
            return;
        }
        if (Constant.isSzwk || Constant.showShop) {
            L.i(Tag, "  有在出货或者发送温控中，等待下次 ");
            cancelFifteenCountTime();
            cancelTwoCountTime();
            return;
        }
        L.i(Tag, isclose ? " 关闭紫外灯指令 " : "开启紫外灯指令");
        isOffLinght = isclose ? 0 : 1;
        int composed = ShareUtils.getInstance().getInt(ShareKey.BOARD_NUM, 1);
        Constant.isUvlamp = true;
        for (int i = 10; i < 10 + composed; i++) {
            Ttys3Utils.getInstance().LEDSetting(i, "0", "1", isclose ? "0" : "1", 15, 15);
        }
        Constant.isUvlamp = false;
    }

    Timer timer;
    TimerTask timerTask;
    int isCheckstatus = 0;//区分检测执行完 的状态
    int Io2_status = 1;//查询的人体感应状态

    /**
     * 检测人体感应  对紫外灯进行操作
     * Io2_status 0-无人，1-有人
     */
    public void checkTimerBodyInduction() {
        L.i(Tag, " 人体感应 === ");
        checkCycleLamp();
        checkCancel();
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                mCurrentTime = ShareUtils.getInstance().getInt(ShareKey.CURRENT_TIME, 0);
                Io2_status = ZtlManager.getInstance().smdtReadExtrnalGpioValue(2);
                L.i(Tag, " 人体感应 ==感应状态  = ", Io2_status, "是否触摸=" + isSomeone, isCheckstatus, "已用时间=" + mCurrentTime);
                if ((Io2_status == 1 || isSomeone) && isCheckstatus != 1) {
                    L.i(Tag, "人体感应 1-有人 ");
                    isCheckstatus = 1;
                    sendLedLamp(true);

                } else if (Io2_status == 0 && isCheckstatus <= 1 && !isSomeone) {
                    L.i(Tag, "人体感应 0-无人 ");
                    isCheckstatus = 2;
                    mCurrentTime = ShareUtils.getInstance().getInt(ShareKey.CURRENT_TIME, 0);
                    if (mCurrentTime >= countTime && totalCycle) {
                        L.i(Tag, "  每个周期内的开启紫外灯的时间已经完成 无法再次开启  等待下个周期吧 ");
                        return;
                    }
                    checkFifteenCountTimeLamp();
                }
            }
        };
        timer.schedule(timerTask, 100, 3000);
    }


    /**
     * 取消循环计时查询人体感应状态
     */
    public void checkCancel() {
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
        if (timer != null) {
            timer.purge();
            timer.cancel();
            timer = null;
        }
    }

    /**
     * 取消延迟后的15s 计时
     */
    public void cancelFifteenCountTime() {
        if (timeUtils3 != null) {
            timeUtils3.cancel();
        }

    }

    /**
     * 取消累计时间的俩分钟计时
     */
    public void cancelTwoCountTime() {
        if (timeUtils2 != null) {
            timeUtils2.cancel();
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        checkCancel();
        cancelFifteenCountTime();
        cancelTwoCountTime();
        if (timeUtils1 != null) {
            timeUtils1.cancel();
        }
        isCheckstatus = 0;
        isOffLinght = -1;
        totalCycle = false;
        int composed = ShareUtils.getInstance().getInt(ShareKey.BOARD_NUM, 1);
        Constant.isUvlamp = true;
        for (int i = 10; i < 10 + composed; i++) {
            Ttys3Utils.getInstance().LEDSetting(i, "0", "1", "0", 15, 15);
        }
        Constant.isUvlamp = false;
        L.i(Tag, "停止紫外灯服务");
    }
}
